package com.maimao.order.serivce;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.maimao.core.constant.KillConstant;
import com.maimao.core.enums.ExceptionEnum;
import com.maimao.core.enums.IntegralActionType;
import com.maimao.core.exception.MaiMaoDaoException;
import com.maimao.core.exception.MaiMaoKillException;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.DateUtils;
import com.maimao.model.goods.dto.GoodsClickDto;
import com.maimao.model.info.IntegralAction;
import com.maimao.model.kill.dto.KillDto;
import com.maimao.model.order.KillSuccess;
import com.maimao.model.order.Order;
import com.maimao.model.order.OrderGoods;
import com.maimao.model.order.OrderShop;
import com.maimao.model.order.input.CommitOrder;
import com.maimao.model.user.input.UpdateIntegralInput;
import com.maimao.order.client.GoodsClient;
import com.maimao.order.client.IntegralActionClient;
import com.maimao.order.client.KillClient;
import com.maimao.order.client.UserClient;
import com.maimao.order.mapper.KillSuccessMapper;
import com.maimao.order.mapper.OrderGoodsMapper;
import com.maimao.order.mapper.OrderMapper;
import com.maimao.order.mapper.OrderShopMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author MaoLin Wang
 * @date 2021/4/17 5:06 下午
 */
@Service
@Slf4j
public class OrderKillService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderShopMapper orderShopMapper;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private KillSuccessMapper killSuccessMapper;

    @Autowired
    private UserClient userClient;

    @Autowired
    private KillClient killClient;

    @Autowired
    private IntegralActionClient integralActionClient;


    @GlobalTransactional(rollbackFor = Exception.class)
    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void killOrder(Long userId, Long killId, Long orderId) {
        CommitOrder commitOrder = (CommitOrder) redisTemplate.opsForValue().get(KillConstant.KILL_SUCCESS_ORDER + orderId);
        if (commitOrder == null) {
            log.error("秒杀订单不存在,orderId:{}", orderId);
            throw new MaiMaoKillException("秒杀订单不存在");
        }
        Order order = commitOrder.getOrder();
        orderMapper.insert(order);

        List<OrderShop> orderShopList = commitOrder.getOrderShopList();

        Integer freezeIntegral = 0;
        Map<Long, Integer> stockMap = new HashMap<>();
        if (ObjectUtil.isNotEmpty(orderShopList)) {
            //秒杀订单只有一个商品
            OrderShop orderShop = orderShopList.get(0);
            orderShopMapper.insert(orderShop);

            List<OrderGoods> orderGoodsList = orderShop.getOrderGoodsList();

            if (ObjectUtil.isNotEmpty(orderGoodsList)) {
                OrderGoods orderGoods = orderGoodsList.get(0);
                Result<Long> brandRes = goodsClient.queryBrandIdByGoodsId(orderGoods.getGoodsId());
                if (brandRes == null || brandRes.getData() == null) {
                    throw new MaiMaoKillException("查询品牌出错");
                }
                freezeIntegral += orderGoods.getIntegral() == null ? 0 : orderGoods.getIntegral();

                orderGoods.setOrderShopId(orderShop.getId());
                orderGoods.setBrandId(brandRes.getData());
                stockMap.put(orderGoods.getSkuId(), orderGoods.getNum());
                orderGoodsMapper.insert(orderGoods);
                //秒杀成功记录
                killSuccessMapper.insert(new KillSuccess().setCreateTime(DateUtils.now()).setKillId(killId).setUserId(userId));
            }
        }
        //修改库存
        goodsClient.updateStock(1, stockMap);
        killClient.reduceStock(new KillDto().setKillId(killId));
        if (freezeIntegral > 0) {
            userClient.updateIntegral(UpdateIntegralInput.builder()
                    .integral(0)
                    .freezeIntegral(freezeIntegral)
                    .cancel(false)
                    .useIntegral(false)
                    .userId(userId).build());
            saveIntegralAction(orderId, userId, freezeIntegral, 0, false, false);
        }
    }

    private void saveIntegralAction(Long orderId, Long userId, Integer freezeIntegral, Integer totalIntegral, Boolean useIntegral, Boolean cancel) {
        List<IntegralAction> actionList = Lists.newArrayListWithCapacity(2);
        if (freezeIntegral > 0) {
            IntegralAction.IntegralActionBuilder builder = IntegralAction.builder().createTime(DateUtils.now()).num(freezeIntegral)
                    .relatedId(orderId)
                    .userId(userId);
            if (cancel) {
                builder.freeze(IntegralActionType.GOODS_OUT_FREEZE.getFreeze())
                        .incr(IntegralActionType.GOODS_OUT_FREEZE.getIncr())
                        .type(IntegralActionType.GOODS_OUT_FREEZE.getType());
            } else {
                builder.freeze(IntegralActionType.GOODS_IN_FREEZE.getFreeze())
                        .incr(IntegralActionType.GOODS_IN_FREEZE.getIncr())
                        .type(IntegralActionType.GOODS_IN_FREEZE.getType());
            }
            actionList.add(builder.build());
        }
        if (actionList.size() > 0) {
            Result<Void> result = integralActionClient.saveBatch(actionList);
          /*  if (result == null || !result.isFlag()) {
//                globalATTractionAspect.doAfterReturning(null);
            }*/

        }
    }
}
